package rabbitmq.rpc;

import com.rabbitmq.client.*;
import rabbitmq.constant.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName RpcClient
 * @Description 客户端 发送请求(携带replyTo correlationID)并接收响应(检验correlationID)
 * @Author ZJX
 * @Date 2025/1/8 06:32
 * @Version 1.0
 **/
public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//        1. 创建连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

//        2. 创建 channel 声明队列
        Channel channel = connection.createChannel();
        channel.queueDeclare(Constants.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(Constants.RPC_RESPONSE_QUEUE,true,false,false,null);

//        3.发送请求
        String correlationId = UUID.randomUUID().toString();
        String message = "hello rpc!";
        AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                .replyTo(Constants.RPC_RESPONSE_QUEUE)
                .correlationId(correlationId)
                .build();
        channel.basicPublish("",Constants.RPC_REQUEST_QUEUE,props, message.getBytes(StandardCharsets.UTF_8));

//        4. 接收响应
        final BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String respMsg = new String(body);
                System.out.println("接收到响应信息"+respMsg);
                if (correlationId.equals(properties.getCorrelationId())){
                    blockingQueue.add(respMsg);
                }
            }
        };
        channel.basicConsume(Constants.RPC_RESPONSE_QUEUE,true,consumer);
        String take = blockingQueue.take();
        System.out.println("[RPC 响应结果]: "+take);
        channel.close();
    }
}

